package com.jxb.myshop.web.filter;

import com.jxb.myshop.common.Constant;
import com.jxb.myshop.common.ResponseCode;
import com.jxb.myshop.common.ResponseResult;
import com.jxb.myshop.services.UserServices;
import com.jxb.myshop.services.impl.UserServicesImpl;
import com.jxb.myshop.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "Filter02_AutoLogin", value = "/login.jsp")
/**
 * @author: JXB
 * @Description: 判断用户是否自动登录
 * @date: 2022/9/18 17:55
 * @param:  * @param null
 * @return: {@link null}
**/
public class Filter02_AutoLogin implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        // 在用户请求中获取cookie
        Cookie[] cookies = request.getCookies();
        // 设置一个字符串变量，用于记录用户是否自动登录
        String auto = null;
        for (Cookie cookie : cookies) {
            // 判断用户是否自动登录
            if (cookie.getName().equals(Constant.SystemConstant.AUTO_LOGIN)) {
                // 用户有设置自动登录的cookie就赋值给auto
                auto = cookie.getValue();
                // 找到cookie打断循环
                break;
            }
        }
        if (auto != null) {
            //先把cookie的值进行解码,并拆分为用户名和用户密码
            // 用户名:密码
            // 用户名:密码 使用:拆分 下标0就是用户名,下标1就是密码
            String username = Base64Utils.decode(auto).split(":")[0];
            String password = Base64Utils.decode(auto).split(":")[1];
            // 创建业务层进行登录
            UserServices us = new UserServicesImpl();
            ResponseResult rr = us.doVerify(username, password);
            // 判断响应回来的ResponseResult的code值是否是成功的值
            // 成功就把user的数据放入session中，失败就进行放行操作
            if (rr.getCode() == ResponseCode.SUCCESS.getCode()) {
                //登录成功,把用户数据保存到session,并重定向到首页
                request.getSession().setAttribute(Constant.SystemConstant.IS_LOGIN,rr.getData());
                response.sendRedirect("/index.jsp");
                return;
            }else{
                chain.doFilter(request, response);
            }
        }else{
            // 用户没有设置自动登录就放行用户去登录
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
